<script setup>
import { Down } from '@icon-park/vue-next'
import Search from './search.vue'

const router = useRouter()
const route = useRoute()

const status = reactive({
    loadTip: '加载中...',//列表加载时的提示
    orderBy: {//排序
        key: route.query.orderby_key,//排序字段
        sort: ''//排序类型desc或asc
    }
})

const data = reactive({
    list: [],//列表数据
    page: {//列表分页数据
        current: Number(route.query.page) || 1,//默认第几页
        size: Number(route.query.pageSize) || config.table.dataCount,//每页显示数量
        total: 0,//总条数
    },
    checked: []//list选中id
})
const tableRef = ref()//table row选中用到

onMounted(() => {
    getList(route.query)
    //排序显示赋值
    const sort = route.query.orderby_sort
    if (sort == 'desc') {
        status.orderBy.sort = 'descending'
    } else if (sort == 'asc') {
        status.orderBy.sort = 'ascending'
    }
})

//获取数据
const getList = (query) => {
    query = func.clearData(query)
    status.loadTip = '加载中...'
    data.page.current = Number(query.page) || 1
    router.push({ path: route.path, query: query });
    //开始请求
    axios.get('/user/list', {
        params: { ...query, begin: (data.page.current - 1) * data.page.size, size: data.page.size }
    }).then(response => {
        data.list = response.data.list
        data.page.total = Number(response.data.total)
        status.loadTip = Object.keys(data.list).length > 0 ? '加载完成' : '未查询到数据'
        data.checked = []
    }).catch(error => {
        status.loadTip = '服务器返回出错'
    })
}

//按照id删除
const deleteItems = (ids) => {
    if (typeof ids != 'object') ids = [ids]//后台需要接收格式为:[2,3,4]
    axios.post('/user/delete', {
        ids: ids
    }).then(response => {
        sys.tip(response, () => { getList(route.query) })
    })
}
//导出数据
const exportList = () => {
    sys.download('/user/listExport', {
        params: route.query,
        name: '用户列表.xlsx',
    })
}
//table点击列选中
const cellClick = (row, cell) => {
    if ([0, 1].indexOf(cell.no) != -1) {//table中点击列如需其他列选中,需加入对应索引
        tableRef.value.toggleRowSelection(row)
    }
}
//table表头点击排序
const sortChange = (table) => {
    let key = table.prop
    let sort = ''
    //与后台接轨重命名key与value
    if (table.order == 'descending') {
        sort = 'desc'
    } else if (table.order == 'ascending') {
        sort = 'asc'
    } else {
        key = ''
    }
    getList({ ...route.query, 'page': '', 'orderby_key': key, 'orderby_sort': sort })
}
</script>

<template>
    <div>
        <Breadcrumb :title="['用户']" />
        <el-card class="list">
            <template #header>
                <div class="flex-2">
                    <Search v-show="data.checked.length == 0" @getList="getList" />
                    <el-space v-show="data.checked.length > 0">
                        <el-popconfirm width="200" :title="'确定要删除已选择的' + data.checked.length + '项内容吗?'"
                            @confirm="deleteItems(data.checked)">
                            <template #reference>
                                <el-button type="danger" plain>删除选择项</el-button>
                            </template>
                        </el-popconfirm>
                        <el-button type="warning" plain
                            @click="() => { tableRef.clearSelection(); data.checked = [] }">取消所有选中</el-button>
                        <el-text>已选择{{ data.checked.length }}条数据</el-text>
                    </el-space>
                    <el-space class="last-child-mr0">
                        <el-button type="primary" v-if="$power('/user/edit')" plain
                            @click="router.push('/user/edit?back=' + encodeURIComponent(route.fullPath))">添加</el-button>
                        <el-dropdown trigger="click" v-if="$power('/userGroup/list') || $power('/user/listExport')">
                            <el-button type="primary" plain>
                                <span>更多操作</span>
                                <Down />
                            </el-button>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item v-if="$power('/userGroup/list')"
                                        @click="router.push('/userGroup/list?back=' + encodeURIComponent(route.fullPath))">用户组</el-dropdown-item>
                                    <el-dropdown-item v-if="$power('/user/listExport')"
                                        @click="exportList()">按查询条件导出数据</el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </el-space>
                </div>
            </template>
            <el-table stripe ref="tableRef" :empty-text="status.loadTip" :data="data.list" @sort-change="sortChange"
                @cell-click="cellClick" :default-sort="{ prop: status.orderBy.key, order: status.orderBy.sort }"
                :row-class-name="({ row }) => { return data.checked.indexOf(row.id) !== -1 ? 'selected-row' : '' }"
                @selection-change="(list) => { data.checked = list.map(obj => obj.id) }">
                <el-table-column fixed type="selection" width="55" />
                <el-table-column fixed prop="id" label="Id" width="80" sortable="custom" />
                <el-table-column prop="username" label="用户名" width="180" />
                <el-table-column prop="group.name" label="用户组" width="180" />
                <el-table-column prop="nickname" label="昵称" width="180" />
                <el-table-column prop="time_create" label="注册时间" width="200" sortable="custom" />
                <el-table-column prop="" label="" />
                <el-table-column fixed="right" label="操作" width="100">
                    <template #default="scope">
                        <el-link class="mr10" type="primary"
                            @click="router.push('/user/edit?id=' + scope.row.id + '&back=' + encodeURIComponent(route.fullPath))">
                            <span v-if="$power('/user/info') && $power('/user/edit')">修改</span>
                            <span v-else-if="$power('/user/info')">详情</span>
                        </el-link>
                        <el-popconfirm v-if="$power('/user/delete')" :hide-after="0" width="200"
                            :title="'确定要删除【' + scope.row.username + '】吗?'" @confirm="deleteItems(scope.row.id)">
                            <template #reference>
                                <el-link type="danger">删除</el-link>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <Page @change="(val) => getList({ ...route.query, page: val })"
                @sizeChange="(size) => { data.page.size = size; getList({ ...route.query, pageSize: size, page: 1 }); }"
                :page="{ ...data.page }" />
        </el-card>
    </div>
</template>

<style scoped lang="scss"></style>
